//
//  YCShopViewController.m
//  YCSchool
//
//  Created by Yanglixia on 16/4/30.
//  Copyright © 2016年 yanglinxia. All rights reserved.
//  商城  参照GOOfficialStoreViewController.m

#import "YCShopViewController.h"
#import "YCShopHeadCollectionViewCell.h"
#import "YCShopProductCollectionViewCell.h"

@interface YCShopViewController ()<UICollectionViewDataSource,UICollectionViewDelegate,UICollectionViewDelegateFlowLayout,YCShopProductCellDelegate,UITableViewDataSource,UITableViewDelegate>

// tableView相关的
@property (nonatomic, strong) UICollectionView *coverCollectionView;// 头部
@property (nonatomic, strong) UIScrollView *categoryScrollView;//sectionHead
@property (nonatomic, strong) UICollectionView *productCollectionView; //cell

/** 分类选中的按钮 */
@property (nonatomic, strong) UIButton *currentSelectedBtn;

@property (nonatomic, strong) UILabel *shopTipLabel;
@property (nonatomic, strong) UIView *footView;
@property (nonatomic, strong) UILabel *numberLabel;
@property (nonatomic, strong) UILabel *priceLabel;
@property (nonatomic, strong) UIButton *nextButton;
@property (nonatomic, strong) NSMutableArray *shoppingCartArray;
@property (nonatomic, strong) NSString *supplierId;
@property (nonatomic, strong) UICollectionViewFlowLayout *collectionFlowLayout;//商品collectview布局

@property (nonatomic, strong) NSMutableArray *coversArray;
@property (nonatomic, strong) NSMutableArray *categoryArray;
//@property (nonatomic, strong) GOMerchant *merchant;
//@property (nonatomic, strong) GOOfficialStoreClassificationModel *currentCategory;
@property (nonatomic, strong) NSMutableDictionary *productDictionary;
@property (nonatomic, strong) UIView *selectedUnderLine;

@property (nonatomic, strong) UITableView *tableView;

@property (nonatomic) CGFloat height;


@end

@implementation YCShopViewController

#pragma mark - 属性获取-懒加载

// 表
- (UITableView *)tableView
{
    if(!_tableView)
    {
        _tableView = [[UITableView alloc] initWithFrame:self.view.bounds style:UITableViewStylePlain];
        _tableView.dataSource = self;
        _tableView.delegate = self;
        _tableView.sectionHeaderHeight = 40.0;//分类高度
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        _tableView.tableHeaderView = self.coverCollectionView;
        _tableView.backgroundColor = [UIColor yc_colorWithUInt:0xf0f0f0];
        _tableView.rowHeight = self.productCollectionView.frame.size.height;
    }
    return _tableView;
}

// 店铺详情label
- (UILabel *)shopTipLabel
{
    if (!_shopTipLabel)
    {
        _shopTipLabel = [[UILabel alloc] init];
        _shopTipLabel.text = @"店铺详情";//这里改为"走进一乘 魅力一乘"
        _shopTipLabel.textColor = [UIColor whiteColor];
        _shopTipLabel.alpha = 0.5;
        _shopTipLabel.textAlignment = NSTextAlignmentCenter;
        _shopTipLabel.font = [UIFont systemFontOfSize:14];
        _shopTipLabel.layer.borderWidth = 1.0;
        _shopTipLabel.layer.borderColor = [UIColor colorWithWhite:1 alpha:0.8].CGColor;
        _shopTipLabel.layer.cornerRadius = 30 / 2;
        _shopTipLabel.backgroundColor = [UIColor blackColor];
        _shopTipLabel.layer.masksToBounds = YES;
    }
    
    return _shopTipLabel;
}


// tableView头部view
- (UICollectionView *)coverCollectionView
{
    if (!_coverCollectionView)
    {
        UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
        layout.scrollDirection = UICollectionViewScrollDirectionHorizontal;
        layout.minimumInteritemSpacing = 0;
        layout.minimumLineSpacing = 0;
        layout.itemSize = CGSizeMake(kScreenWidth, kScreenWidth/2);
        
        _coverCollectionView = [[UICollectionView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, kScreenWidth / 2.0) collectionViewLayout:layout];
        _coverCollectionView.dataSource = self;
        _coverCollectionView.delegate = self;
        _coverCollectionView.pagingEnabled = YES;
        _coverCollectionView.backgroundColor = [UIColor clearColor];
        _coverCollectionView.showsHorizontalScrollIndicator = YES;
        _coverCollectionView.showsVerticalScrollIndicator = NO;
        [_coverCollectionView registerClass:[YCShopHeadCollectionViewCell class] forCellWithReuseIdentifier:@"shopHeadCollectionViewCell"];
    }
    
    return _coverCollectionView;
}

// tableView的cell --卡片(商品展示)
- (UICollectionView *)productCollectionView
{
    if (!_productCollectionView)
    {
        _collectionFlowLayout = [[UICollectionViewFlowLayout alloc] init];
        _collectionFlowLayout.scrollDirection = UICollectionViewScrollDirectionVertical;
        _collectionFlowLayout.minimumInteritemSpacing = 2;
        _collectionFlowLayout.minimumLineSpacing = 10;
        _collectionFlowLayout.itemSize = CGSizeMake((kScreenWidth-36)/2,(kScreenWidth-36)/2+60);
        _collectionFlowLayout.sectionInset = UIEdgeInsetsMake(10, 10, 10, 10);
        
        _productCollectionView = [[UICollectionView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth,300) collectionViewLayout:_collectionFlowLayout];
        _productCollectionView.dataSource = self;
        _productCollectionView.delegate = self;
        _productCollectionView.showsHorizontalScrollIndicator = NO;
        _productCollectionView.showsVerticalScrollIndicator = NO;
        _productCollectionView.backgroundColor = [UIColor yc_colorWithUInt:0xf0f0f0];
        [_productCollectionView registerClass:[YCShopProductCollectionViewCell class] forCellWithReuseIdentifier:@"shopProductCollectionViewCell"];
    }
    
    return _productCollectionView;
}

// tableview的footerview
- (UIView *)footView
{
    if (!_footView)
    {
        _footView = [[UIView alloc] init];
        _footView.backgroundColor = [UIColor whiteColor];
    }
    
    return _footView;
}

// 商品名称
- (UILabel *)numberLabel
{
    if (!_numberLabel)
    {
        _numberLabel = [[UILabel alloc] init];
        _numberLabel.layer.borderWidth = 1.0;
        _numberLabel.layer.borderColor = [UIColor grayColor].CGColor;
        _numberLabel.layer.cornerRadius = 25/2;
        _numberLabel.layer.masksToBounds = YES;
        _numberLabel.text = @"0";
        _numberLabel.textAlignment = NSTextAlignmentCenter;
        _numberLabel.textColor = [UIColor grayColor];
        _numberLabel.font = [UIFont systemFontOfSize:16];
    }
    
    return _numberLabel;
}

// 价格
- (UILabel *)priceLabel
{
    if (!_priceLabel)
    {
        _priceLabel = [[UILabel alloc] init];
        _priceLabel.textColor = [UIColor grayColor];
        _priceLabel.text = @"￥0.00";
        _priceLabel.font = [UIFont systemFontOfSize:16];
    }
    
    return _priceLabel;
}

- (NSMutableArray *)shoppingCartArray
{
    if (!_shoppingCartArray) {
        _shoppingCartArray = [NSMutableArray array];
    }
    return _shoppingCartArray;
}

- (NSMutableDictionary *)productDictionary
{
    if (!_productDictionary) {
        _productDictionary = [NSMutableDictionary dictionary];
    }
    return _productDictionary;
}

- (NSMutableArray *)categoryArray
{
    if (!_categoryArray) {
        _categoryArray = [NSMutableArray array];
        [_categoryArray addObjectsFromArray:@[@"明星产品",@"汽车保养",@"汽车装饰",@"汽车配件",@"汽车型号",@"汽车保养",@"汽车装饰"]];//测试用
    }
    return _categoryArray;
}

- (NSMutableArray *)coversArray
{
    if (!_coversArray) {
        _coversArray = [NSMutableArray array];
        //测试用
        [_coversArray addObjectsFromArray:@[@"http://img1.3lian.com/2015/w7/98/d/22.jpg",
                                           @"http://img1.3lian.com/2015/w7/90/d/5.jpg",
                                           @"http://img1.3lian.com/2015/w7/90/d/1.jpg",
                                           @"http://pic37.nipic.com/20140209/8821914_163234218136_2.jpg",
                                           @"http://pic39.nipic.com/20140226/18071023_162553457000_2.jpg",
                                            @"http://imgsrc.baidu.com/forum/pic/item/645b8701a18b87d6e716e197070828381e30fdae.jpg"]];
    }
    return _coversArray;
}

#pragma mark - 分类scrollview内部控制
- (void)addTitlesBtn
{
    NSUInteger count = self.categoryArray.count;
    for (NSUInteger i = 0;  i < count; i++) {

        UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
        btn.titleLabel.font = [UIFont systemFontOfSize:14];
        [btn setTitle:self.categoryArray[i] forState:UIControlStateNormal];
        [btn setTitle:self.categoryArray[i] forState:UIControlStateSelected];
        [btn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
        [btn setTitleColor:[UIColor yc_colorWithUInt:0xe62129] forState:UIControlStateSelected];
        
        [btn addTarget:self action:@selector(titleBtnClick:) forControlEvents:UIControlEventTouchUpInside];
        
        CGFloat btnW = kScreenWidth / 3.0;
        CGFloat btnH = 40;
        CGFloat btnX = i * btnW;
        CGFloat btnY = 0;
        btn.frame = CGRectMake(btnX, btnY, btnW, btnH);
        [self.categoryScrollView addSubview:btn];

        if (i == 0) {
            [self titleBtnClick:btn];
        }
    }
    CGFloat contentW = count * kScreenWidth / 3.0;;
    self.categoryScrollView.contentSize = CGSizeMake(contentW, 0);
}
- (void)addUnderLine
{
    UIButton *fistBtn = [self.categoryScrollView.subviews firstObject];
    UIView *underline = [[UIView alloc] init];
    CGFloat underlineH = 2;
    CGFloat underlineW = self.categoryScrollView.yc_width / 3.0;
    CGFloat underlineX = 0;
    CGFloat underlineY = self.categoryScrollView.yc_height - underlineH;
    underline.frame = CGRectMake(underlineX, underlineY, underlineW, underlineH);
    //设置下划线的颜色,根随按钮选中的颜色一致
    underline.backgroundColor = [fistBtn titleColorForState:UIControlStateSelected];
    [self.categoryScrollView addSubview:underline];
    self.selectedUnderLine = underline;
    [fistBtn.titleLabel sizeToFit];
    self.selectedUnderLine.yc_width = fistBtn.titleLabel.yc_width + 20;
    self.selectedUnderLine.yc_centerX = fistBtn.yc_centerX;
}

- (void)titleBtnClick:(UIButton *)btn
{
    self.currentSelectedBtn.selected = NO;
    btn.selected = YES;
    self.currentSelectedBtn = btn;
    
    [self setupTitleCenter:btn];
    
    NSInteger index = [self.categoryScrollView.subviews indexOfObject:btn];
    
    [UIView animateWithDuration:0.2 animations:^{
        self.selectedUnderLine.yc_width = btn.titleLabel.yc_width + 20;
        self.selectedUnderLine.yc_centerX = btn.yc_centerX;
    } completion:nil];
    
    //测试用
    if (index == 0) {
        CGFloat rowHeight = (kScreenWidth - 30) / 2 + 60;
        self.height =  (rowHeight * 10 + (10 + 1) * 10 )/ 2.0;//测试时我们返回的是10个 要除2
        self.productCollectionView.frame = CGRectMake(0, 0, kScreenWidth, self.height);
        [self.tableView reloadData];
    }
    
}
// 让标题居中
- (void)setupTitleCenter:(UIButton *)btn
{
    CGFloat offsetX = btn.center.x - kScreenWidth * 0.5;
    if (offsetX < 0) {
        offsetX = 0;
    }
    CGFloat maxOffsetX = self.categoryScrollView.contentSize.width - kScreenWidth;
    if (offsetX > maxOffsetX) {
        offsetX = maxOffsetX;
    }
    [self.categoryScrollView setContentOffset:CGPointMake(offsetX, 0) animated:YES];
    
}
#pragma mark - 生命周期


- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
    [self.productCollectionView reloadData];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.navigationItem.title = @"一乘驾校";
    [self yc_addBackBarButtonItem];
    [self makeView];
    
    //下拉刷新
    YCWeakSelf;
    self.tableView.mj_header = [YCRefreshHeader headerWithRefreshingBlock:^{
        [weakSelf loadNewData];
    }];
    // 上拉刷新
    self.tableView.mj_footer = [YCRefreshFooter footerWithRefreshingBlock:^{
        [weakSelf loadMoreData];
    }];
    // 一进入就刷新
    [self.tableView.mj_header beginRefreshing];
    
}


- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    YCLog(@"收到内存警告");
}

#pragma mark -

- (void)makeView
{
    [self.view addSubview:self.tableView];
    [self.tableView addSubview:self.shopTipLabel];
    
    [self setupCategoryScrollView];
    
    [self.tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.and.top.and.bottom.and.right.equalTo(@0);
    }];
    
    [self.shopTipLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.equalTo(self.tableView.mas_top).offset((kScreenWidth / 2 - 18));
        make.centerX.equalTo(self.tableView);
        make.width.equalTo(@100);
        make.height.equalTo(@30);
    }];
    
}

- (void)setupCategoryScrollView
{
    UIScrollView *categoryScrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, 40)];
    categoryScrollView.backgroundColor = [UIColor whiteColor];
    categoryScrollView.showsHorizontalScrollIndicator = NO;
    categoryScrollView.showsVerticalScrollIndicator = NO;
    self.categoryScrollView = categoryScrollView;
    [self addTitlesBtn];
    [self addUnderLine];
}

#pragma mark - 数据处理相关
- (void)loadNewData
{
    // 1.添加数据
    
    // 模拟2秒后刷新表格UI
    YCWeakSelf;
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        // 刷新表格
        [weakSelf.tableView reloadData];
        // 拿到当前的下拉刷新控件，结束刷新状态
        [self.tableView.mj_header endRefreshing];
    });
}

// 上拉加载
- (void)loadMoreData
{
    // 添加数据
    BOOL flag = YES;//用来判断是不是还有数据
    
    // 模拟2秒后刷新表格UI
    YCWeakSelf
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        // 刷新表格
        [weakSelf.tableView reloadData];
        
        if (flag) {
            [weakSelf.tableView.mj_footer endRefreshing];//结束上拉刷新
        } else {
            [weakSelf.tableView.mj_footer endRefreshingWithNoMoreData];//没有更多数据可加载
        }
//        weakSelf.tableView.mj_footer.hidden = YES;//只加载一次,只要hiden就可以了
    });
}

#pragma mark - UICollectionView datasource

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    NSInteger count = 0;
    if(collectionView == self.coverCollectionView)
    {
        count = self.coversArray.count;
    }
    else
    {
//        NSMutableArray *array = self.productDictionary[@(self.currentCategory.idNum)];
//        count = array.count;
        count = 10;//测试
    }
    return count;
}

#pragma mark - UICollectionView delegate

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    UICollectionViewCell *cell;
    
    if(collectionView == self.coverCollectionView)
    {
        YCShopHeadCollectionViewCell *cc = [collectionView dequeueReusableCellWithReuseIdentifier:@"shopHeadCollectionViewCell" forIndexPath:indexPath];
        NSString *url = self.coversArray[indexPath.row];
        [cc.imageView yc_setWebImageWithURLString:url holderSize:CGSizeMake(kScreenWidth, kScreenWidth / 2.0)];
        cell = cc;
    }
    else
    {
        
        YCShopProductCollectionViewCell *pcell = [collectionView dequeueReusableCellWithReuseIdentifier:@"shopProductCollectionViewCell" forIndexPath:indexPath];
        pcell.delegate = self;
        
        [pcell.bgView yc_setWebImageWithURLString:@"http://b.hiphotos.baidu.com/image/h%3D200/sign=8de92df279cb0a469a228c395b63f63e/8c1001e93901213f391481d456e736d12f2e9597.jpg" holderSize:self.collectionFlowLayout.itemSize];
        pcell.foodNameLabel.text = @"美女如云";
        pcell.priceLabel.text = @"只要¥300带回家";
        pcell.reduceBtn.hidden = NO;
        pcell.numberLabel.hidden = NO;
        pcell.plusBtn.hidden = NO;
        return pcell;
    }
    
    return cell;
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    
    if(collectionView == self.coverCollectionView)
    {
        YCLog(@"点击了头部collectionView的cell的第:%zd个item",indexPath.item);
//        GOShopIntroductionViewController *vc = [[GOShopIntroductionViewController alloc] initWithMerchant:self.merchant];
//        [self.navigationController pushViewController:vc animated:YES];
    }
    else
    {
//        NSMutableArray *array = self.productDictionary[@(self.currentCategory.idNum)];
//        GOOfficialStoreProductModel *product = array[indexPath.row];
//        GOLoginUser *user = [GOLoginUser loginUser];
//        NSMutableDictionary *ps = [[NSMutableDictionary alloc] init];
//        ps[@"userId"] = user.yanglinxiaOpenID;
//        ps[@"entityId"] = @(product.productId);
//        ps[@"fromuid"] = @"999883236";
//        
//        if(user.userNickName) ps[@"userName"] = user.userNickName;
//        if(user.userHeadPhoto) ps[@"userImgUrl"] = user.userHeadPhoto;
//        if(user.userMobilePhone) ps[@"phone"] = user.userMobilePhone;
//        
//        NSString *url = @"http://www.gmall88.com/gmall/G/normal/p-info.jsp";
//        url = [url go_urlStringWithParams:ps];
        
        // 跳到webView
//        GOWebViewController *vc = [[GOWebViewController alloc] initWithURLString:url];
//        [self.navigationController pushViewController:vc animated:YES];
        
         YCLog(@"点击了cell中的collectionView的cell的第:%zd个item",indexPath.item);
    }
}

#pragma mark -- UITableView delegate

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return 1;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"tableViewCell"];
    if(!cell)
    {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"tableViewCell"];
        [cell.contentView addSubview:self.productCollectionView];//tableviewcell中放商口collectonView
        cell.contentView.backgroundColor = tableView.backgroundColor;
    }
    [self.productCollectionView reloadData];
    return cell;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    return self.categoryScrollView;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return self.height;
}

#pragma mark -- YCShopProductCelldelegate

- (void)shopProductCell:(YCShopProductCollectionViewCell *)cell didTouchUpInsideReduceAndReduceButton:(UIButton *)button
{
    YCLog(@"商品collectionViewCell点击了...");
}


@end
